﻿Imports OpenNETCF.Desktop.Communication
Imports System.IO
Imports System.ComponentModel
Imports Microsoft.Win32



Partial Public Class BrowseDevice
    Private m_rapi As RAPI
    Private m_activeSync As ActiveSync
    Private m_path As String
    Private m_OkCancel As String

    Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub

    Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Try
            treeviewDirectories.AddHandler(TreeViewItem.SelectedEvent, New RoutedEventHandler(AddressOf ItemSelected))
            If isActiveSyncInstalled() Then
                InitializeRAPI()
                If Not LoadDirectories("") Then
                    Throw New Exception
                End If
                treeviewItemDirectory.IsExpanded = True
            Else
                MsgBox("Please install the latest ActiveSynch or WDMC to continue.", MsgBoxStyle.OkOnly, "Synch Error")
            End If
            
        Catch ex As Exception
            MsgBox("Please check if your device is connected.", MsgBoxStyle.OkOnly, "Synch Error")

        End Try

    End Sub

    Private Sub InitializeRAPI()
        Dim m_activesync As ActiveSync
        Try
            m_rapi = New RAPI()
            If m_rapi.DevicePresent Then
                m_rapi.Connect()
                m_activesync = m_rapi.ActiveSync
                Try
                    m_activesync.AutoConnect = True
                Catch exas As Exception
                Finally

                End Try


            End If
        Catch ex As Exception





        End Try
    End Sub

    Private Function LoadDirectories(ByVal directory As String) As Boolean
        Try


            Cursor = Cursors.Wait
            Dim fl As FileList = m_rapi.EnumFiles("*")
            If fl IsNot Nothing Then
                For Each fi As FileInformation In fl
                    If (fi.FileAttributes And CInt(FileAttributes.Directory)) = CInt(FileAttributes.Directory) Then
                        Try
                            Dim node As New TreeViewItem
                            node.Header = fi.FileName
                            node.Name = Replace(fi.FileName, " ", "")
                            node.Tag = fi.FileName
                            treeviewItemDirectory.Items.Add(node)
                            Me.LoadDirectories(directory + fi.FileName, node)
                        Catch ex As Exception

                        End Try
                        
                    End If
                Next
            End If
            treeviewItemDirectory.Items.SortDescriptions.Add(New SortDescription("Header", ListSortDirection.Ascending))
            Cursor = Cursors.Arrow
            Return True
        Catch ex As Exception
            Cursor = Cursors.Arrow
            Return False
        End Try
    End Function

    Private Sub LoadDirectories(ByVal directory As String, ByVal node As TreeViewItem)
        Dim fl As FileList = m_rapi.EnumFiles(directory & "\*")
        If fl IsNot Nothing Then
            For Each fi As FileInformation In fl
                If (fi.FileAttributes And CInt(FileAttributes.Directory)) = CInt(FileAttributes.Directory) Then
                    Dim node1 As New TreeViewItem
                    node1.Header = fi.FileName
                    node1.Tag = (directory & "\") + fi.FileName
                    node.Items.Add(node1)
                    'node.Items.Refresh()
                    Me.LoadDirectories((directory & "\") + fi.FileName, node1)
                End If
            Next
        End If
        node.Items.SortDescriptions.Add(New SortDescription("Header", ListSortDirection.Ascending))
    End Sub

    Private Sub ItemSelected(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        If Not m_rapi.Connected Then
            Return
        End If

        Dim item As TreeViewItem = e.OriginalSource
        m_path = ParsePath(item.Tag) & "\"


        listboxFolderFiles.Items.Clear()
        Dim s As String = ParsePath(item.Tag)
        Dim fl As FileList = m_rapi.EnumFiles(s & "\*")
        If fl IsNot Nothing Then
            For Each fi As FileInformation In fl
                If (fi.FileAttributes And CInt(FileAttributes.Directory)) <> CInt(FileAttributes.Directory) Then
                    listboxFolderFiles.Items.Add(fi.FileName)
                End If
            Next
        End If
        'Dim fl As FileList = m_rapi.EnumFiles(item.Tag)
        'If fl IsNot Nothing Then
        '    For Each fi As FileInformation In fl
        '        If (fi.FileAttributes And CInt(FileAttributes.Directory)) = CInt(FileAttributes.Directory) Then
        '            Dim node1 As New TreeViewItem
        '            node1.Header = fi.FileName
        '            node1.Tag = fi.FileName
        '            item.Items.Add(fi.FileName)
        '            'node.Items.Refresh()

        '            'Me.LoadDirectories((Directory & "\") + fi.FileName, node1)
        '        End If
        '    Next
        'End If
    End Sub

    Private Function ParsePath(ByVal treeNodePath As String) As String
        If Not treeNodePath Is Nothing Then
            If treeNodePath.StartsWith("Root") Then
                Return treeNodePath.Replace("Root", "")
            Else
                Return treeNodePath
            End If
        Else
            Return treeNodePath
        End If
    End Function


    Public Property Path() As String
        Set(ByVal value As String)
            m_path = value
        End Set
        Get
            Return Me.m_path
        End Get
    End Property

    Public ReadOnly Property OkCancel() As String
        Get
            Return Me.m_OkCancel
        End Get
    End Property


    Private Shared Function isActiveSyncInstalled() As Boolean
        Dim syncVersion As Version
        Using reg As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows CE Services")
            If reg Is Nothing Then
                syncVersion = Nothing
                Return False
            End If

            Dim majorVersion As Integer = CInt(reg.GetValue("MajorVersion", 0))
            Dim minorVersion As Integer = CInt(reg.GetValue("MinorVersion", 0))
            Dim buildNumber As Integer = CInt(reg.GetValue("BuildNumber", 0))

            syncVersion = New Version(majorVersion, minorVersion, buildNumber)
        End Using
        Return True
    End Function


    'Sub SetupDocList()

    '    ' Assumes an instance of DocumentList,
    '    ' documentList1, has been declared.
    '    With DocumentList1
    '        .Parent = Me
    '        .Filter = " |*.*| |*.txt;*.xml| |*.pwi;*.pdt| " & _
    '            "|*.pxl;*.psw| |*.jpg;*.gif;*.bmp| |*.wav;*.wmv;*.mpg;"
    '        .FilterIndex = 0
    '        .SelectedDirectory = "Business"
    '    End With

    'End Sub

    '' Handle the DocumentedActivated
    '' event with code to open the file.
    'Private Sub DocList_DocumentActivated(ByVal sender As Object, _
    '    ByVal docevent As Microsoft.WindowsCE.Forms.DocumentListEventArgs) _
    '    Handles DocumentList1.DocumentActivated

    '    StatusBar1.Text = "Activated: " & docevent.Path
    '    ' Add code to open the selected file.

    'End Sub

    '' Handle the DeletingDocument 
    '' event with code to close the file.
    'Private Sub DocList_DeletingDocument(ByVal sender As Object, _
    '    ByVal docevent As Microsoft.WindowsCE.Forms.DocumentListEventArgs) _
    '    Handles DocumentList1.DeletingDocument

    '    StatusBar1.Text = "Deleted: " & docevent.Path
    '    ' Add code to close any instances of the file.

    'End Sub

    '' Handle the SelectedDirectoryChanged
    '' event with code that sets the correct
    '' path for opening and closing files.
    'Private Sub DocList_SelectedDirectoryChanged( _
    '    ByVal sender As Object, ByVal e As System.EventArgs) _
    '    Handles DocumentList1.SelectedDirectoryChanged

    '    StatusBar1.Text = "Folder: " & DocumentList1.SelectedDirectory
    '    ' Add code to access the selected folder to open and close files.    

    'End Sub


    Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnOk.Click
        m_OkCancel = "ok".ToUpper
        Me.Close()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub
End Class
